package com.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;
import com.gulimall.product.dao.ProductAttrValueDao;
import com.gulimall.product.entity.ProductAttrValueEntity;
import com.gulimall.product.service.ProductAttrValueService;
import com.gulimall.product.vo.ProductAttrUpdateVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>());

        return new PageUtils(page);
    }

    @Override
    public void saveSpuProductAttr(List<ProductAttrValueEntity> attrValueEntities) {
        saveBatch(attrValueEntities);
    }

    @Override
    public List<ProductAttrValueEntity> getListForSpu(Long spuId) {
        return list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
    }

    @Transactional
    @Override
    public void updateProductAttr(List<ProductAttrUpdateVo> productAttrUpdateVos, Long spuId) {
        productAttrUpdateVos.forEach(item -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setSpuId(spuId);
            attrValueEntity.setAttrId(item.getAttrId());
            attrValueEntity.setAttrValue(item.getAttrValue());
            attrValueEntity.setQuickShow(item.getQuickShow());

            update(attrValueEntity, new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId).eq("attr_id",
                    item.getAttrId()));
        });
    }
}
